/**
 * 打包爬虫，负责获得数据返回路径
 *
 * @author bian
 * @createDate 2016.9.9
 */
var path = require("path");

var superagentPromisePlugin = require('superagent-promise-plugin');
require('es6-promise').polyfill();
var request = superagentPromisePlugin.patch(require('superagent'));
var charset = require("superagent-charset");
charset(request);

var config = require("./config.json");

var Spider = function (host,port) {
    this.url = "http://" + host + ":" + port;
    this.apiUrl = this.url + "/apis/dev";
    this.cookies = {};
    this.apps = [];
    this.hubs = [];
    this.things = [];
};

Spider.prototype.parseCookies = function(){
    var self = this;
    return request
        .get(self.url)
        .then(function(res){
            self.cookies = res.headers["Cookie"];
            // console.log(self.cookies);
        });
};

Spider.prototype.getAppsData = function (){
    var self = this;
    self.apps = [];
    return request
        .post(self.apiUrl)
        .set("Accept","application/json")
        .set("Content-Type","application/json")
        .set("User-Agent","Mozilla/5.0")
        .send({api: "app.list", params: []})
        .then(function(res){
            var apps = JSON.parse(res.text);
            for(var app of apps){
                self.apps.push({
                    name : app.name,
                    path : app.path,
                    graphs : app.graphs
                });
            }
            // console.log(self.apps);
            return self.apps;
        });
};

Spider.prototype.getHubList = function(){
    var self = this;
    self.hubs = [];
    return request
        .post(self.apiUrl)
        .set("Accept","application/json")
        .set("Content-Type","application/json")
        .set("User-Agent","Mozilla/5.0")
        .send({api: "hub.list", params: []})
        .then(function(res){
            var data = JSON.parse(res.text);
            var hub;
            for(hub of data){
                self.hubs.push(hub.id);
            }
            // console.log(self.hubs);
            return self.hubs;
        });
};


Spider.prototype.getThingsData = function(){
    var self = this;
    self.things = [];
    return self
        .getHubList()
        .then(function(){
            var hubs = self.hubs;
            return request
                .post(self.apiUrl)
                .set("Accept","application/json")
                .set("Content-Type","application/json")
                .set("User-Agent","Mozilla/5.0")
                .send({api: "hub.get",params:[self.hubs]})
                .then(function(res) {
                    var data = JSON.parse(res.text);
                    var hub;
                    var thing;
                    for(hub of data){
                        for(thing of hub.things){
                            if(! thing.path) break;
                            self.things.push(thing.path);
                        }
                    }
                    return self.things;
                });
        });

};

Spider.prototype.getBundlePath = function () {
    var self = this;
    return self
        .getThingsData()
        .then(function (things) {
            var re = /(.*(hope-demo)\/\w*)/i;
            var paths = [];
            for(thing of things){
                var result = re.exec(thing);
                if(result && paths.indexOf(result[0]) === -1){
                    paths.push(result[0]);
                }
            }
            var thingsPath = paths[0];
            var appPath = path.join(thingsPath,"../center/appbundle");

            re = /(.*)\/node_modules\//i;
            var root = re.exec(thingsPath)[1];

            return {
                root : root,
                appPath : appPath,
                thingsPath : thingsPath
            };
        });
};

Spider.prototype.startWorkflow = function(id){
    var self = this;
    return request
        .post(self.apiUrl)
        .send({api:"graph.start",params:[[id],true]})
        .then(function(res){
            return JSON.parse(res.status);
        });
};

Spider.prototype.stopWorkflow = function(id){
    var self = this;
    return request
        .post(self.apiUrl)
        .send({api:"graph.stop",params:[[id]]})
        .then(function(res){
            return JSON.parse(res.status);
        });
};

module.exports = Spider;